package com.qf.mybatis.result.utils;/*
*王浩政 
*whz
2022/9/2
14:18
*小米商城
*/

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;


public class MybatisUtils {

    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 获取链接
     * */
    public static SqlSession openSession() {
        //创建并保存到threadlocal
        SqlSession sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /*
     * 提交事务
     * */
    public static void commit() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.commit();
        }
    }

    /*
     *回滚事务
     * */
    public static void rollback() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.rollback();
        }
    }

    /*
     * 关闭连接
     * */
    public static void close() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
            //移除，防止内存泄露
            threadLocal.remove();
        }
    }

    /*
     * 获取mapper对象
     * */
    public static <T> T getMapper(Class<T> clazz) {
        SqlSession sqlSession = threadLocal.get();
        //没有的情况下创建
        if (sqlSession == null) {
            //创建一个并保存
            sqlSession = openSession();
      //      threadLocal.set(sqlSession);
        }
        //返回mapper
        return sqlSession.getMapper(clazz);
    }
}
